package com.test.task;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.test.dao.HibernateUtil;
import com.test.model.Student;
import com.test.util.DateUtil;

public class ActiveStudentWorkerByhibernate implements Task{
	public final static int SIZE = 10000;
	public Object params;
	public Object parentThread;
	
	public ActiveStudentWorkerByhibernate(Object params,Object parentThread){
		this.params = params;
		this.parentThread = parentThread;
	}
	
	public void execute() {
		System.out.println(getTaskName()+"子线程任务开始；");
		Long beginTime = System.currentTimeMillis(); 
		int round = (Integer)params;
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		Query query = session.createQuery(" from student where status='1' and activeTime is null");
		query.setFirstResult(round*SIZE);
		query.setMaxResults(SIZE);
		List list = query.list();
		for(int i=0;i<list.size();i++){
			Student s = (Student)list.get(i);
			s.setActiveTime(DateUtil.getCurrentTime());
			s.setActiveFrom("HIBERNATE");
			session.update(s);
			if(i%100==0){
				session.flush(); 
				session.clear(); 
			}
		}
		tx.commit(); 
		if(session!=null && session.isOpen())
			session.close(); 
		Long endTime = System.currentTimeMillis(); 
		System.out.println(getTaskName()+"执行完毕耗时"+(endTime-beginTime)+"毫秒，"+(endTime-beginTime)/1000+"秒，准备回调父任务");
		((ActiveStudentTask)parentThread).childCallBack(round);
		System.out.println(getTaskName()+"回调成功，子任务结束");
	}

	public String getTaskName() {
		return ((ActiveStudentTask)parentThread).getTaskName()+"[ActiveStudentWorkerByhibernate#"+(Integer)params+"轮]";
	}

	public void run() {
		execute();
	}

}
